from selenium import webdriver
import time

from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from random import randint, choice

from Console import console
from settings import STANDART_DELAY
import requests
import undetected_chromedriver.v2 as uc
import os


class ChromeBrowser:
    fake_brows = []

    def __init__(self):
        self.driver = None
        page = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
        js = page.json()
        brows = js['browsers']
        for el in brows:
            if el == 'chrome':

                for br in brows[el]:
                    self.fake_brows.append(br)


    def get_user_agent(self, others=False):
        browser = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36"

        if others:
            browser = choice(self.fake_brows)

        ua = "user-agent=" + browser
        return ua

    def GetUrl(self, url, delay=60, use_old_browser=False, PROXY=None):
        selenium_url = "http://localhost:4444/wd/hub"

        caps = {'browserName': 'chrome'}
        options = webdriver.ChromeOptions()

        options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument('--headless')
        options.add_argument(self.get_user_agent(others=True))
        # options.add_argument(
        # "user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36")

        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        if PROXY:
            options.add_argument('--proxy-server=https://%s' % PROXY)

        self.driver = webdriver.Remote(command_executor=selenium_url, desired_capabilities=caps, options=options)

        # action = ActionChains(driver)

        self.driver.maximize_window()

        script = "window.open('{}')".format(url)

        self.driver.execute_script(script)
        time.sleep(1)
        self.driver.switch_to.window(self.driver.window_handles[1])
        self.driver.save_screenshot("photos/gg1.png")
        console.send_message(self.driver.title)
        time.sleep(3)

        console.send_message(self.driver.current_url)
        self.driver.save_screenshot("photos/gg.png")

        for i in range(delay // STANDART_DELAY + (delay % STANDART_DELAY) * STANDART_DELAY // STANDART_DELAY):
            els = self.driver.find_elements(value="button.btn.btn-primary.g-recaptcha", by=By.CSS_SELECTOR)
            if els:
                els[0].click()
                ActionChains(self.driver).click(els[0]).perform()
                time.sleep(3)

                console.send_message("Clicking on button")
            self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))  # session timeout - 60 sec
            time.sleep(STANDART_DELAY)
            self.driver.save_screenshot("photos/g1g.png")

        self.driver.close()
        self.driver.quit()

    def GetBotUrl(self, url, delay=60, use_old_browser=False, PROXY=None):
        selenium_url = "http://localhost:4444/wd/hub"

        caps = {'browserName': 'chrome'}
        options = webdriver.ChromeOptions()
        options.add_argument("start-maximized")
        options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument('--headless')
        options.add_argument(self.get_user_agent(others=True))
        
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        if PROXY:
            options.add_argument('--proxy-server=https://%s' % PROXY)

        self.driver = webdriver.Remote(command_executor=selenium_url, desired_capabilities=caps, options=options)

        self.driver.maximize_window()

        script = "window.open('{}')".format(url)

        self.driver.execute_script(script)
        time.sleep(1)
        self.driver.switch_to.window(self.driver.window_handles[1])
        self.driver.save_screenshot("photos/gg1.png")
        console.send_message(self.driver.title)
        self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))  # session timeout - 60 sec
        time.sleep(10)
        self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))  # session timeout - 60 sec
        time.sleep(10)

        els = self.driver.find_elements(value="button.btn.btn-primary.g-recaptcha", by=By.CSS_SELECTOR)
        if els:
            els[0].click()
            ActionChains(self.driver).click(els[0]).perform()
            time.sleep(3)

            console.send_message("Clicking on button")
            self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))  # session timeout - 60 sec
            time.sleep(STANDART_DELAY)
            self.driver.save_screenshot("photos/g1g.png")


        telegram_link =self.driver.find_elements(value="tgme_page_extra", by=By.CLASS_NAME)
        bot_name = self.driver.find_elements(value= "tgme_page_title", by=By.CLASS_NAME)

        tg_link, bt_name = None, None
        if telegram_link:
            tg_link = telegram_link[0].text
        if bot_name:
            bt_name = bot_name[0].text

        self.driver.close()
        self.driver.quit()
        return [tg_link, bt_name]

    def GetGroupUrl(self, url, delay=60, use_old_browser=False, PROXY=None):
        selenium_url = "http://localhost:4444/wd/hub"

        caps = {'browserName': 'chrome'}
        options = webdriver.ChromeOptions()
        options.add_argument("start-maximized")
        options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument('--headless')
        options.add_argument(self.get_user_agent(others=True))

        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--no-sandbox")
        if PROXY:
            options.add_argument('--proxy-server=https://%s' % PROXY)

        self.driver = webdriver.Remote(command_executor=selenium_url, desired_capabilities=caps, options=options)

        script = "window.open('{}')".format(url)

        self.driver.execute_script(script)
        time.sleep(0.5)
        self.driver.switch_to.window(self.driver.window_handles[1])
        self.driver.save_screenshot("photos/gg1.png")
        console.send_message(self.driver.title)
        self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))
        time.sleep(1)
        self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))
        time.sleep(5)
        els = self.driver.find_elements(value="button.btn.btn-primary.g-recaptcha", by=By.CSS_SELECTOR)

        if els:
            els[0].click()
            ActionChains(self.driver).click(els[0]).perform()
            time.sleep(3)

            console.send_message("Clicking on button")
            self.driver.execute_script("window.scrollTo(0, {})".format(randint(1, 15)))  # session timeout - 60 sec
            time.sleep(STANDART_DELAY)
            self.driver.save_screenshot("photos/g1g.png")

        channel_name = self.driver.find_elements(value="tgme_page_title", by=By.CLASS_NAME)
        channel_link = self.driver.find_elements(value="tgme_action_button_new", by= By.CLASS_NAME)
        channel_link_text, channel_name_text = None, None
        if channel_name:
            channel_name_text = channel_name[0].text
        if "Telegram: Contact" in self.driver.title:
            channel_link_text = self.driver.title
            channel_link_text = channel_link_text.replace("Telegram: Contact ", "")

        return [channel_name_text, channel_link_text]


if __name__ == '__main__':
    pass
